package com.easycarebn.main.appointment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.easycarebn.main.adapter.AappointmentAdapter;
import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.data.AppointmentItem;
import com.easycarebn.request.data.AppointmentListResponse;
import com.easycarebn.request.data.DataItem;
import com.easycarebn.request.data.DataItemResponse;
import com.easycarebn.request.data.StatusCode;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.service.request.OnRequest;
import com.timbacsi.main.MainActivity;
import com.timbacsi.main.R;

public class Appointment {
	private View mView;
	private Activity mActivity;
	private AappointmentAdapter adapter = null;
	private List<AppointmentItem> listAppointment = null;

	private String mAppointmentCode;
	private String mDoctorName = "";
	private String mAppointmentDate = "";
	private String mStartDate = "";
	private String mEndDate = "";
	private String mAppointmentStatus = "waiting";
	private String mRangeDate = "3";

	private TextView tvStartDate;
	private EditText edAppointmentCode;

	private Calendar mCalBirthday;
	private ListView listmessage;
	private LinearLayout lineOptionQlhk;
	private String mToken;
	private int mPage = 0;
	private int mLastPage = 0;
	private View mFooter;

	public Appointment(Activity activity, View view, String status) {
		this.mView = view;
		this.mActivity = activity;
		this.mAppointmentStatus = status;
		UserResponse userResponse = Utils.getUserLogin(mActivity);
		listAppointment = new ArrayList<AppointmentItem>();

		if (userResponse != null)
			mToken = userResponse.getToken();
		mFooter = mActivity.getLayoutInflater().inflate(R.layout.load_more,
				null);
		listmessage = (ListView) mView.findViewById(R.id.listmessage);
		listmessage.addFooterView(mFooter);
		edAppointmentCode = (EditText) mView
				.findViewById(R.id.edAppointmentCode);
		edAppointmentCode.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.length() == 1) {
					getList();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		lineOptionQlhk = (LinearLayout) mView.findViewById(R.id.lineOptionQlhk);

		listmessage.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bundle bundle = new Bundle();
				bundle.putString(Utils.KEY_ID, listAppointment.get(arg2)
						.getId() + "");
				Utils.intentToDetailt(mActivity, Utils.APPOINTMENT_DETAIL,
						bundle);
			}
		});
		tvStartDate = (TextView) mView.findViewById(R.id.startDate);
		final TextView spin_option = (TextView) mView
				.findViewById(R.id.spin_option);
		spin_option.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final List<DataItem> listDataItems = new ArrayList<DataItem>();
				// for (int i = 0; i < 10; i++) {

				listDataItems.add(new DataItem(4, "Tất cả"));
				listDataItems.add(new DataItem(1, "Lịch khám trong ngày"));
				listDataItems.add(new DataItem(2, "Lịch khám trong tuần"));
				listDataItems.add(new DataItem(3, "Lịch khám trong tháng "));

				// }
				Utils.addMenuTop(listDataItems, mActivity, v, new IResult() {

					@Override
					public void onDisplay(int arg1, String arg2) {
						Log.d("arg2", arg2);
						spin_option.setText(listDataItems.get(arg1).getName());

						if (arg2.equals("4")) {
							mRangeDate = "";
							mAppointmentDate = "";
							tvStartDate.setVisibility(View.GONE);
						} else {
							tvStartDate.setVisibility(View.VISIBLE);
							mRangeDate = arg2;
							mAppointmentDate = tvStartDate.getText().toString()
									.trim();
						}
						resetPage();
						getList();

					}
				});

			}
		});
		adapter = new AappointmentAdapter(mActivity, listAppointment,
				new IResult() {

					@Override
					public void onDisplay(int arg1, String arg2) {
						if (arg1 == Activity.RESULT_CANCELED)
							removeHenkham(listAppointment.get(
									Integer.parseInt(arg2)).getId());
					}
				});
		listmessage.setAdapter(adapter);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		tvStartDate.setText(dateFormat.format(cal.getTime()));

		tvStartDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mCalBirthday == null) {
					mCalBirthday = Calendar.getInstance();
				}
				new DatePickerDialog(mActivity, new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						mCalBirthday.set(Calendar.YEAR, year);
						mCalBirthday.set(Calendar.MONTH, monthOfYear);
						mCalBirthday.set(Calendar.DAY_OF_MONTH, dayOfMonth);
						tvStartDate.setText(year + "-" + (1 + monthOfYear)
								+ "-" + dayOfMonth);
						mRangeDate = "";
						mAppointmentDate = tvStartDate.getText().toString()
								.trim();
						resetPage();
						getList();
					}
				}, mCalBirthday.get(Calendar.YEAR), mCalBirthday
						.get(Calendar.MONTH), mCalBirthday
						.get(Calendar.DAY_OF_MONTH)).show();
			}
		});
		ImageButton btnSearch = (ImageButton) mView
				.findViewById(R.id.btnSearch);
		btnSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				resetPage();
				getList();
			}
		});

	
		

		Button btnLoadmore = (Button) mFooter.findViewById(R.id.btnLoadMore);
		btnLoadmore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getList();
			}
		});

		resetPage();
		getList();
	}

	public void resetPage() {
		mRangeDate = "";
		mAppointmentDate = "";
		listAppointment.clear();
		mPage = 0;
		mLastPage = 0;
	}

	public void getList() {
		if (mToken.isEmpty()) {
			return;
		}
		Log.d("status", mAppointmentStatus + " ");
		MainActivity.mLoadingData.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);

		mAppointmentCode = edAppointmentCode.getText().toString().trim();
		ServerController.getInstance(mActivity).requestGetListAppointment(
				mToken, mAppointmentCode, mDoctorName, mAppointmentDate,
				mStartDate, mEndDate, mAppointmentStatus, mRangeDate,
				mPage + 1, new OnRequest<AppointmentListResponse>() {

					@Override
					public void onSuccess(AppointmentListResponse data) {
						Log.d("AppointmentListResponse", data.getAppointments()
								.size() + "");

						MainActivity.mLoadingData.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						lineOptionQlhk.setVisibility(View.VISIBLE);

						mPage = data.getPaging().getCurrentPage();
						mLastPage = data.getPaging().getLastPage();
						if (mLastPage > mPage) {
							mFooter.setVisibility(View.VISIBLE);
						} else {
								listmessage.removeFooterView(mFooter);
						}

						listAppointment.addAll(data.getAppointments());
						adapter.notifyDataSetChanged();

					}

					@Override
					public void onError(int errorCode, String message) { //
						MainActivity.mLoadingData.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						if (errorCode == 0) {
							Utils.onResumeRequest(mActivity, mView,
									new IResult() {
										@Override
										public void onDisplay(int arg1,
												String arg2) {
											getList();
										}
									});
						}
					}

				});

	}

	public void removeHenkham(final int id) {
		Utils.showDialogConfirm(mActivity, "Bạn có muốn hủy cuộc hẹn",
				new IResult() {

					@Override
					public void onDisplay(int arg1, String arg2) {
						if (arg1 == Activity.RESULT_OK) {
							cancelAppointment(id);
						}
					}
				});
	}

	public void cancelAppointment(final int id) {
		MainActivity.mLoadingData.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);

		ServerController.getInstance(mActivity).requestCancelAppointment(
				mToken, id, new OnRequest<DataItemResponse>() {

					@Override
					public void onSuccess(DataItemResponse data) {
						MainActivity.mLoadingData.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);

						if (data.getCode() == StatusCode.OK) {
							adapter.removeItem(id);
						}
						adapter.notifyDataSetChanged();

					}

					@Override
					public void onError(int errorCode, String message) {
						MainActivity.mLoadingData.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);

					}

				});
	}
}
